package com.example.mylock;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * description: SemaphoreDemo <br>
 * date: 2021/3/22 14:21 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 7; i++) {
            new Thread(()->{
                try {
                    // 占用资源
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢占了一个位置");

                    TimeUnit.SECONDS.sleep(3);

                    System.out.println(Thread.currentThread().getName()+"释放抢占资源");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },i+"").start();
        }
    }

}
